package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * str
 * 686. 重复叠加字符串匹配
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/22 9:29
 */
public class RepeatedStringMatch {

    public static void main(String[] args) {
        RepeatedStringMatch test = new RepeatedStringMatch();


        // 3
//        String a = "abcd";
//        String b = "cdabcdab";

        // 2
//        String a = "a";
//        String b = "aa";

        // 1
//        String a = "a";
//        String b = "a";

        // -1
//        String a = "abc";
//        String b = "wxyz";

        // 1
//        String a = "aa";
//        String b = "a";

        // -1
        String a = "aaaaaaaaaaaaaaaaaaaaaab";
        String b = "ba";

        int i = test.repeatedStringMatch(a, b);
        System.out.println(i);
    }


    public int repeatedStringMatch(String a, String b) {
        String item = b;
        b = b.replace(a, "*");
        int length = b.length();
        if (item.equals(b)) {
            if (a.contains(b)) {
                return 1;
            }
            if ((a + a).contains(b)) {
                return 2;
            }
            return -1;
        }
        int m = 0;
        for (int i = 0; i < length; i++) {
            if (b.charAt(i) == '*') {
                m = i;
                break;
            }
        }
        int n = 0;
        for (int i = length - 1; i >= 0; i--) {
            if (b.charAt(i) == '*') {
                n = i;
                break;
            }
        }
        for (int i = m; i <= n; i++) {
            if (b.charAt(i) != '*') {
                return -1;
            }
        }
        if (!a.endsWith(b.substring(0, m))) {
            return -1;
        }
        if (!a.startsWith(b.substring(n + 1))) {
            return -1;
        }
        return n - m + 1 + (m == 0 ? 0 : 1) + (n == length - 1 ? 0 : 1);
    }

}
